package view.ui
{
	
	import events.MyEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.geom.Rectangle;
	
	import loader.SinglePicLoader;
	
	import utils.BitMapMethod;
	import utils.CopyToImageFile;
	import utils.MyTimer;
	
	public class CutOutWorker extends ProgressView
	{
		private var source:File;
		private var targetFolder:File;
		public var index:uint=0;
		private var singlePicLoader:SinglePicLoader;
		private var sourceBM:Bitmap;
//		private var x_vector:Vector.<Number>;
//		private var y_vector:Vector.<Number>;
		private var imageSaver:CopyToImageFile;
		private var analyzeTimer:MyTimer;
		private var analyzeTime:Number=0.04;
		private var x_pos:Number=0;
		private var y_pos:Number=0;
		private var nowAnalyzePosition:uint=0;
		private var source_width:Number;
		private var source_height:Number;
		private var area:Number;
		private var rate:Number=0;
		private var left:Number=NaN;
		private var right:Number=NaN;
		private var top:Number=NaN;
		private var bottom:Number=NaN;
		private var stop:Boolean=false;
		private var fileNameTxt:FileNameTextField;
		
		
		private var left_x_pos:Number=0;
		private var left_y_pos:Number=0;
		
		private var right_x_pos:Number=0;
		private var right_y_pos:Number=0;
		
		private var top_x_pos:Number=0;
		private var top_y_pos:Number=0;
		
		private var bottom_x_pos:Number=0;
		private var bottom_y_pos:Number=0;
		
		private var left_percent:Number=0;
		private var right_percent:Number=0;
		private var top_percent:Number=0;
		private var bottom_percent:Number=0;
		
		private var leftChecked:Number=NaN;
		private var rightChecked:Number=NaN;
		private var topChecked:Number=NaN;
		private var bottomChecked:Number=NaN;
		
//		private var test:Sprite;
		public function CutOutWorker(s:File,t:File)
		{
			super();
			source=s;
			targetFolder=t;
		}
		
		public function stopWork():void
		{
			stop=true;
			if(analyzeTimer)
			{
				analyzeTimer.GC();
				analyzeTimer=null;
			}
		}
		
		private function addFileNameTxt():void
		{
			if(!fileNameTxt)
			{
				fileNameTxt=new FileNameTextField();
				var filename:String=source.name;
				fileNameTxt.text=filename.substr(0,filename.length-4);
				this.addChild(fileNameTxt);
				fileNameTxt.x=10;
				fileNameTxt.y=20;
			}
			
		}
		
		public function wait():void
		{
			this.text="等待";
			progress(1);
			addFileNameTxt();
		}
		
		public function startWork():void
		{
			addFileNameTxt();		
			this.text="加载图片";
			trace("source.url="+source.url);
			singlePicLoader=new SinglePicLoader(source.url,handlePicLoaded);
		}
		
		private function handlePicLoaded(bm:Bitmap):void
		{
			singlePicLoader=null;
			sourceBM=bm;
			var bmpd:BitmapData=sourceBM.bitmapData;
			this.progress(5);
			this.text="正在分析图片";
			
		
			try
			{
				source_width=bmpd.width;
				source_height=bmpd.height;
				area=bmpd.width*bmpd.height;
				right_x_pos=source_width;
				bottom_y_pos=source_height;
				
			}
			catch(e:Error)
			{
				this.dispatchEvent(new MyEvent("fileError",this.index));
				this.red();
				this.text=e.message;
				return;
			}
			analyzeTimer=new MyTimer(analyze,analyzeTime);
			analyzeTimer.start();
		}
		
		
		
		private function run():void
		{
			var count:Number=nowAnalyzePosition%4;
			switch(count)
			{
				case 0:
					if(isNaN(left))
					{
						getLeft();
					}
					else
					{
						left_percent=25;
						if(isNaN(right))
						{
							getRight();
						}
						else if(isNaN(top))
						{
							getTop();
						}
						else if(isNaN(bottom))
						{
							getBottom();
						}
					}
					break;
				case 1:
					if(isNaN(right))
					{
						getRight();
					}
					else
					{
						right_percent=25;
						if(isNaN(left))
						{
							getLeft();
						}
						else if(isNaN(top))
						{
							getTop();
						}
						else if(isNaN(bottom))
						{
							getBottom();
						}
					}
					break;
				case 2:
					if(isNaN(top))
					{
						getTop();
					}
					else
					{
						top_percent=25;
						if(isNaN(left))
						{
							getLeft();
						}
						else if(isNaN(right))
						{
							getRight();
						}
						else if(isNaN(bottom))
						{
							getBottom();
						}
					}
					break;
				case 3:
					if(isNaN(bottom))
					{
						getBottom();
					}
					else
					{
						bottom_percent=25;
						if(isNaN(left))
						{
							getLeft();
						}
						else if(isNaN(right))
						{
							getRight();
						}
						else if(isNaN(top))
						{
							getTop();
						}
					}
					break;
			}
			
		}
		
		private function analyze():void
		{
			if(stop)
			{
				analyzeTimer.GC();
				analyzeTimer=null;
			}
//			run();
			if(isNaN(left))
			{
				getLeft();
			}
			else
			{
				left_percent=25;
			}
			if(isNaN(right))
			{
				getRight();
			}
			else
			{
				right_percent=25;
				
			}
			if(isNaN(top))
			{
				getTop();
			}
			else
			{
				top_percent=25;
			}
			if(isNaN(bottom))
			{
				getBottom();
			}
			else
			{
				bottom_percent=25;
			}
			nowAnalyzePosition++;
			
			
			
			
			
			if(!isNaN(leftChecked)&&!isNaN(rightChecked)&&!isNaN(topChecked)&&!isNaN(bottomChecked))
			{
				var _left:Number=leftChecked;
				var _right:Number=rightChecked;
				var _top:Number=topChecked;
				var _bottom:Number=bottomChecked;
				if(!isNaN(left))
				{
					_left=left;
				}
				if(!isNaN(right))
				{
					_right=right;
				}
				if(!isNaN(top))
				{
					_top=top;
				}
				if(!isNaN(bottom))
				{
					_bottom=bottom;
				}
				var _area:Number=(_right-_left)*(_bottom-_top)/(source_width*source_height);
				
				
				
				rate=(1-_area)*100;
				this.progress(5+rate*.8);
			}
				
			
			if(left_percent==25&&right_percent==25&&top_percent==25&&bottom_percent==25)
			{
				analyzeTimer.GC();
				analyzeTimer=null;
				right=right-left;
				bottom=bottom-top;
				drawBm(new Rectangle(left,top,right,bottom));
			}
		}
		
		private function getLeft():void
		{
			if(!isNaN(left))return;
			var bmpd:BitmapData=sourceBM.bitmapData;
			var pixelValue:uint;
			var alphaValue:uint;
			var startY:Number=0;
			var endY:Number=source_height;
			if(!isNaN(bottom))
			{
				endY=bottom;
			}
			else if(!isNaN(bottomChecked))
			{
				endY=bottomChecked;
			}
			if(!isNaN(top))
			{
				startY=top;
			}
			else if(!isNaN(topChecked))
			{
				startY=topChecked;
			}
			trace("get left now x is "+left_x_pos);
			trace("startY="+startY);
			trace("endY="+endY);
			for(var i:uint=startY;i<endY;i++)
			{
				pixelValue = bmpd.getPixel32(left_x_pos, i);
				alphaValue = pixelValue >> 24 & 0xFF;
				if(alphaValue!=0)
				{
					left=left_x_pos;
					//					trace("get left "+left);
					return;
				}
			}
			leftChecked=left_x_pos;
			left_x_pos++;
			if(left_x_pos==source_width)
			{
				left=left_x_pos;
			}
		}
		
		private function getRight():void
		{
			if(!isNaN(right))return;
			var bmpd:BitmapData=sourceBM.bitmapData;
			var pixelValue:uint;
			var alphaValue:uint;
			var startY:Number=0;
			var endY:Number=source_height;
			if(!isNaN(bottom))
			{
				endY=bottom;
			}
			else if(!isNaN(bottomChecked))
			{
				endY=bottomChecked;
			}
			if(!isNaN(top))
			{
				startY=top;
			}
			else if(!isNaN(topChecked))
			{
				startY=topChecked;
			}
			trace("get right now x is "+right_x_pos);
			trace("startY="+startY);
			trace("endY="+endY);
			for(var i:uint=startY;i<endY;i++)
			{
				pixelValue = bmpd.getPixel32(right_x_pos, i);
				alphaValue = pixelValue >> 24 & 0xFF;
				if(alphaValue!=0)
				{
					right=right_x_pos;
					trace("get right "+right);
					return;
				}
			}
			rightChecked=right_x_pos;
			right_x_pos--;
			if(right_x_pos==0)
			{
				right_x_pos=left_x_pos;
			}
		}
		
		private function getTop():void
		{
			if(!isNaN(top))return;
			var bmpd:BitmapData=sourceBM.bitmapData;
			var pixelValue:uint;
			var alphaValue:uint;
			var startX:Number=0;
			var endX:Number=source_width;
			if(!isNaN(right))
			{
				endX=right;
			}
			else if(!isNaN(rightChecked))
			{
				endX=rightChecked;
			}
			if(!isNaN(left))
			{
				startX=left;
			}
			else if(!isNaN(leftChecked))
			{
				startX=leftChecked;
			}
			trace("get top now y is "+top_y_pos);
			trace("startX="+startX);
			trace("endX="+endX);
			for(var i:uint=startX;i<endX;i++)
			{
				pixelValue = bmpd.getPixel32(i, top_y_pos);
				alphaValue = pixelValue >> 24 & 0xFF;
				if(alphaValue!=0)
				{
					top=top_y_pos;
					trace("get top "+top);
					return;
					
				}
			}
			topChecked=top_y_pos;
			top_y_pos++;
			if(top_y_pos==source_height)
			{
				top=top_y_pos;
			}
		}
		
		private function getBottom():void
		{
			if(!isNaN(bottom))return;
			var bmpd:BitmapData=sourceBM.bitmapData;
			var pixelValue:uint;
			var alphaValue:uint;
			var startX:Number=0;
			var endX:Number=source_width;
			if(!isNaN(right))
			{
				endX=right;
			}
			else if(!isNaN(rightChecked))
			{
				endX=rightChecked;
			}
			if(!isNaN(left))
			{
				startX=left;
			}
			else if(!isNaN(leftChecked))
			{
				startX=leftChecked;
			}
			trace("get bottom now y is "+bottom_y_pos);
			trace("startX="+startX);
			trace("endX="+endX);
			for(var i:uint=startX;i<endX;i++)
			{
				pixelValue = bmpd.getPixel32(i, bottom_y_pos);
				alphaValue = pixelValue >> 24 & 0xFF;
				if(alphaValue!=0)
				{
					bottom=bottom_y_pos;
					trace("get bottom "+bottom);
					return;
					
				}
			}
			bottomChecked=bottom_y_pos;
			bottom_y_pos--;
			if(bottom_y_pos==0)
			{
				bottom_y_pos=top_y_pos;
			}
		}
		
		private function getMin(s:Vector.<Number>):Number
		{
			var num:uint=s[0];
			var length:uint=s.length;
			for(var i:uint=1;i<length;i++)
			{
				num=Math.min(num,s[i]);
			}
			return num;
		}
		
		private function getMax(s:Vector.<Number>):Number
		{
			var num:uint=s[0];
			var length:uint=s.length;
			for(var i:uint=1;i<length;i++)
			{
				num=Math.max(num,s[i]);
			}
			return num;
		}
		
		private function drawBm(rect:Rectangle):void
		{
			if(stop)
			{
				return;
			}
			this.text="开始绘制图片";
			var bmp:Bitmap=BitMapMethod.draw(sourceBM,rect);
			this.progress(90);
			this.text="绘制图片完成";
			savePic(bmp);
		}
		
		private function savePic(bm:Bitmap):void
		{
			if(stop)
			{
				return;
			}
			if(!imageSaver)
			{
				imageSaver=new CopyToImageFile();
				imageSaver.addEventListener("imageSaved",handlePngSaved);
			}
			this.progress(95);
			this.text="正在保存图片";
			var savePosition:File= targetFolder.resolvePath(source.name);
			imageSaver.savePng(bm,new Rectangle(0,0,bm.width,bm.height),true,savePosition,true);
		}
		
		private function handlePngSaved(e:Event):void
		{
			if(stop)
			{
				return;
			}
			this.progress(100);
			this.text="图片保存成功";
			this.dispatchEvent(new MyEvent("fileOk",this.index));
			sourceBM.bitmapData.dispose();
			imageSaver.removeEventListener("imageSaved",handlePngSaved);
		}
		
	}
}